<?php


namespace app\zmt\controller;


use app\zmt\model\NavModel;
use app\zmt\validate\NavValidate;
use cmf\controller\AdminBaseController;

class NavController extends AdminBaseController
{
    //显示导航菜单
    public function index(){
        //获取搜索字段
        $key = input('key');
        $where = [];
        if($key){
            $where[] = ['title','like','%'.$key.'%'];
        }
        //查询
        $list = NavModel::order(['list_order'=>'DESC'])
            ->where($where)
            ->paginate(10);
        $this->assign('list',$list);
        return $this->fetch();
    }
    //页面添加
    public function add(){
        return $this->fetch();
    }
    //添加方法
    public function addPost(){
        $data = input('post.','');
        $validate = new NavValidate();
        $res = $validate->scene('add')->check($data);
        if(!$res){
            $this->error($validate->getError());
        }
        $image = $data['image'];
        $url = cmf_get_image_url($image);
        if(NavModel::create([
            'title' => $data['title'],
            'url' => $data['url'],
            'image' => $url,
        ])){
            $this->success('添加成功','index');
        }else{
            $this->error('添加失败');
        }
    }
    //修改页面显示
    public function edit(){
        $id = input('id');
        $nav = NavModel::find($id);
        $this->assign('nav',$nav);
        return $this->fetch();
    }
    //修改方法
    public function editPost(){
        $data = input('post.');
        //验证器
        $validate = new NavValidate();
        $res = $validate->scene('edit')->check($data);
        if(!$res){
            $this->error($validate->getError());
        }
//        查询用户是否存在
        $edit = NavModel::find($data['id']);
        if(!$edit){
            $this->error('未查询到该数据');
        }
        $image = $data['image'];
        $url = cmf_get_image_url($image);
//        halt($url);
        $edit->title= $data['title'];
        $edit->url= $data['url'];
        $edit->image= $url;

        if ($edit->save()) {
            $this->success('修改成功','Nav/index');
        } else {
            $this->error('修改失败');
        }
    }
    //单条删除
    public function delete(){
        $id = input('id/d','');
        $isExist = NavModel::find($id);
        //判断该id是否存在
        if(!$isExist){
            $this->error('该数据不存在');
        }
        $del = NavModel::destroy($id);
        if($del){
            $this->success('删除成功','Nav/index');
        }else{
            $this->error('删除失败');
        }
    }
    //排序
    public function order()
    {
        $model = new NavModel();
        parent::listOrders($model);
        $this->success('排序成功');
    }
}
